package com.pengheng.server;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * @author zhangzhihai
 * @date 2024/7/15
 */

@Component
@Slf4j
public class NettyServer {

    @Value("${netty.port}")
    private int port;
    /**
     * 用于接收客户端连接
     */
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    /**
     * 用于处理I/O操作
     */
    EventLoopGroup workerGroup = new NioEventLoopGroup();


    @PostConstruct
    public void start() throws InterruptedException {
        // 用于启动服务端的引导类
        ServerBootstrap serverBoot = new ServerBootstrap();
        serverBoot.group(bossGroup, workerGroup)
                // 设置Channel的选项
                .option(ChannelOption.SO_BACKLOG, 128)
                // 设置Channel类型为NIO
                .channel(NioServerSocketChannel.class)
                // 设置日志处理器
                .handler(new LoggingHandler(LogLevel.INFO))
                // 保持连接的活跃状态
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                //将小的数据包包装成更大的帧进行传送，提高网络负载
                .childOption(ChannelOption.TCP_NODELAY, true)
                // 初始化客户端连接的SocketChannel
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) {
                        // 添加处理器到ChannelPipeline
                        ch.pipeline().addLast(new StringDecoder(), new StringEncoder(), new ServerHandler());
                    }
                });
        // 绑定端口并启动
        ChannelFuture serverFuture = serverBoot.bind(port).sync();
        if (serverFuture.isSuccess()) {
            log.info("启动 Netty Server");
        }
    }

    @PreDestroy
    public void destroy() throws InterruptedException {
        bossGroup.shutdownGracefully().sync();
        workerGroup.shutdownGracefully().sync();
        log.info("关闭Netty");
    }
}